﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Threading;
using System.Xml.XPath;
using WindowsPhoneToolbox.Util;
using MessageBox = System.Windows.MessageBox;
using OpenFileDialog = Microsoft.Win32.OpenFileDialog;
using AppRes = WindowsPhoneToolbox.Resources;

namespace WindowsPhoneToolbox.Controls
{
    /// <summary>
    /// Interaction logic for WindowsPhoneControl.xaml
    /// </summary>
    public partial class WindowsPhoneControl
    {
        private static readonly Color BrightGreen = Color.FromArgb(0xFF, 0x01, 0xD3, 0x28);

        private static bool IsInDesignModeStatic
        {
            get
            {
                return
                    (bool)
                    DependencyPropertyDescriptor.FromProperty(DesignerProperties.IsInDesignModeProperty, typeof(FrameworkElement)).Metadata.DefaultValue;
            }
        }

        private bool _animateColor;

        private void InitializeRuntime()
        {
            if (IsInDesignModeStatic) return;

            barText.Text = "";
            BuildProgressBar.Value = 0;
            ShowPanelConnect(false);
            ShowPanelBuild(false);
            ShowPanelPhone(true);
            ShowPanelApps(false);
            ShowPanelDeploy(false);
            ShowPanelExplorer(false);
            ShowPanelManifestEdit(false);
        }

        public WindowsPhoneControl()
        {
            InitializeComponent();
            InitializeRuntime();
            // Animate from Blue to bright green by default
            StartColor = Colors.Blue;
            EndColor = BrightGreen;
        }

        public Color StartColor { get; set; }
        public Color EndColor { get; set; }

        public bool AnimateColor
        {
            get { return _animateColor; }
            set
            {
                _animateColor = value;

                // Create or remove a drop shadow effect
                if (_animateColor && BuildProgressBar.Effect == null)
                    BuildProgressBar.Effect = new DropShadowEffect();
                else if (!_animateColor && BuildProgressBar.Effect != null)
                    BuildProgressBar.Effect = null;
            }
        }

        // Get/set the progress bar value
        public double Value
        {
            get { return BuildProgressBar.Value; }
            set
            {
                BuildProgressBar.Foreground = AnimateColor ? new SolidColorBrush(Lerp(StartColor, EndColor, value)) : new SolidColorBrush(BrightGreen);

                BuildProgressBar.Value = value;
            }
        }

        // Get/set the progress bar text
        public string Text
        {
            get { return barText.Text; }
            set { barText.Text = value; }
        }

        // Calculate a linear interpolation between two colors
        private Color Lerp(Color first, Color second, double percentage)
        {
            var a = (byte)((second.A - first.A) * percentage + first.A);
            var r = (byte)((second.R - first.R) * percentage + first.R);
            var g = (byte)((second.G - first.G) * percentage + first.G);
            var b = (byte)((second.B - first.B) * percentage + first.B);

            return Color.FromArgb(a, r, g, b);
        }

        public void ShowPanelWelcome()
        {
            ShowPanelWelcome(true);
        }

        public void ShowPanelWelcome(bool show)
        {
            if (show)
            {
                ShowPanelConnect(false);
                ShowPanelApps(false);
                ShowPanelDeploy(false);
                ShowPanelExplorer(false);
                ShowPanelManifestEdit(false);
                Welcome.Show();
            }
            else
            {
                Welcome.Hide();
            }
        }
        
        public void ShowPanelWelcomeTimer(int seconds)
        {
            Welcome.ShowTimer(seconds);
        }

        public void ShowPanelManifestEdit()
        {
            ShowPanelManifestEdit(true);
        }

        public void ShowPanelManifestEdit(bool show)
        {
            if (show)
            {
                ShowPanelConnect(false);
                ShowPanelApps(false);
                ShowPanelDeploy(false);
                ShowPanelExplorer(false);
                ShowPanelWelcome(false);

            }
            PanelEditManifest.Visibility = show ? Visibility.Visible : Visibility.Collapsed;
        }

        public void ShowPanelExplorer()
        {
            ShowPanelExplorer(true);
        }

        public void ShowPanelExplorer(bool show)
        {
            if (show)
            {
                ShowPanelConnect(false);
                ShowPanelApps(false);
                ShowPanelDeploy(false);
                ShowPanelManifestEdit(false);
                ShowPanelWelcome(false);
            }
            PanelExplorer.Visibility = show ? Visibility.Visible : Visibility.Collapsed;
        }

        public void ShowPanelConnect()
        {
            ShowPanelConnect(true);
        }

        public void ShowPanelConnect(bool show)
        {
            if (show)
            {
                ShowPanelPhone();
                ShowPanelApps(false);
                ShowPanelDeploy(false);
                ShowPanelExplorer(false);
                ShowPanelManifestEdit(false);
                ShowPanelWelcome(false);
            }
            PanelConnect.Visibility = show ? Visibility.Visible : Visibility.Collapsed;
        }

        public void ShowPanelBuild()
        {
            ShowPanelBuild(true);
        }

        public void ShowPanelBuild(bool show)
        {
            if (show)
            {
                ShowPanelPhone(false);
                ShowPanelApps(false);
                ShowPanelDeploy(false);
                ShowPanelExplorer(false);
                ShowPanelConnect(false);
                ShowPanelManifestEdit(false);
                ShowPanelWelcome(false);
            }
            gridbuild.Visibility = show ? Visibility.Visible : Visibility.Collapsed;
        }

        public void ShowPanelPhone()
        {
            ShowPanelPhone(true);
        }

        public void TargetConnect(string fileManifest, string targetDevice)
        {
            if (!string.IsNullOrEmpty(fileManifest))
            {
                try
                {
                    var document = new XPathDocument(fileManifest);
                    var navigator = document.CreateNavigator().SelectSingleNode("//App");
                    if (navigator != null)
                    {
                        var deployIsolateFile = new WpDeployApplication
                        {
                            Guid = navigator.GetAttribute("ProductID", string.Empty).Replace("{", "").Replace("}", ""),
                            Title = navigator.GetAttribute("Title", string.Empty),
                            RenameTitle = string.Empty
                        };
                        WpIsolateSaveData.Current.AddData(deployIsolateFile);
                    }
                    if (!PanelConnect.IsConnected)
                    {
                        ShowPanelConnect();
                        PanelConnect.TargetConnect(targetDevice);
                    }
                    else
                    {
                        ShowPanelApps();
                    }
                }
                // ReSharper disable EmptyGeneralCatchClause
                catch
                // ReSharper restore EmptyGeneralCatchClause
                {
                }
            }
        }

        public void ShowPanelPhone(bool show)
        {
            gridCell.Visibility = show ? Visibility.Visible : Visibility.Collapsed;
        }

        public void ShowPanelApps()
        {
            ShowPanelApps(true);
        }

        public void ShowPanelApps(bool show)
        {
            if (show)
            {
                ShowPanelConnect(false);
                ShowPanelDeploy(false);
                ShowPanelExplorer(false);
                ShowPanelManifestEdit(false);
                ShowPanelWelcome(false);
                try
                {
                    var oldcur = Cursor;
                    Cursor = System.Windows.Input.Cursors.Wait;
                    PanelAppsInst.RemoteApplications = WPhoneDevice.ListApplicationsInstalled();
                    PanelAppsCore.RemoteApplications = WPhoneDevice.ListApplicationsCore();
                    PanelPhoneSettings.RemoteApplications = WPhoneDevice.ListSettingsCore();
                    Cursor = oldcur;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Show/Resfreh Error : " + ex.Message, AppRes.TitleWindows);
                }
                PanelAppsInst.Expanded = true;
                PanelAppsCore.Expanded = false;
                PanelPhoneSettings.Expanded = false;
            }
            PanelAppsInst.Visibility = show ? Visibility.Visible : Visibility.Collapsed;
            PanelAppsCore.Visibility = show ? Visibility.Visible : Visibility.Collapsed;
            PanelPhoneSettings.Visibility = show ? Visibility.Visible : Visibility.Collapsed;
        }

        public void ShowPanelDeploy()
        {
            ShowPanelDeploy(true);
        }

        public void ShowPanelDeploy(bool show)
        {
            if (show)
            {
                ShowPanelConnect(false);
                ShowPanelApps(false);
                ShowPanelExplorer(false);
                ShowPanelManifestEdit(false);
                ShowPanelWelcome(false);
            }
            PanelDeploy.Visibility = show ? Visibility.Visible : Visibility.Collapsed;
        }

        private void ManifestEditClick(object sender, RoutedEventArgs e)
        {
            ShowPanelManifestEdit();
        }

        private void PhoAppsMenuClick(object sender, RoutedEventArgs e)
        {
            ShowPanelApps();
        }

        private void XapDeployMenuClick(object sender, RoutedEventArgs e)
        {
            ShowPanelDeploy();
        }

        private void ConnectMenuClick(object sender, RoutedEventArgs e)
        {
            ShowPanelConnect();
        }

        private void PanelConnectConnectCommand(object sender, RoutedEventArgs e)
        {
            var connected = ((ConnectPhoneEvent)e).IsConnected;
            if (connected)
            {
                PanelConnect.DeviceInfo.IsExpanded = true;
                CelPhoneMsg.Text = Common.GetStatus();
            }
            else
            {
                PanelConnect.DeviceInfo.IsExpanded = false;
                PanelAppsCore.RemoteApplications = null;
                PanelAppsInst.RemoteApplications = null;
                PanelPhoneSettings.RemoteApplications = null;
                CelPhoneMsg.Text = Common.GetStatus();
                if (PanelEditManifest.Visibility != Visibility.Visible)
                {
                    ShowPanelConnect();
                }
            }
        }

        private void PanelActionCommand(object sender, RoutedEventArgs e)
        {
            var temp = (AppPhoneEvent)e;
            if (WPhoneDevice.CurrentDevice == null || (WPhoneDevice.CurrentDevice != null && !WPhoneDevice.CurrentDevice.IsConnected()))
            {
                MessageBox.Show(AppRes.ConnectionLost, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            switch (temp.Action)
            {
                case AppPhoneAction.Launch:
                    {
                        CelPhoneMsg.Tag = CelPhoneMsg.Text;
                        CelPhoneMsg.Text = AppRes.WaitLaunch;
                        Dispatcher.BeginInvoke(DispatcherPriority.Background, new EventAppHandle(LaunchApp), temp);
                    }
                    break;
                case AppPhoneAction.Explorer:
                    {
                        CelPhoneMsg.Tag = CelPhoneMsg.Text;
                        CelPhoneMsg.Text = AppRes.WaitReadFiles;
                        ShowPanelExplorer();
                        var arg = new AppPhoneEvent(AppPhoneAction.Launch, string.Empty, temp.Guid, string.Empty);
                        Dispatcher.BeginInvoke(DispatcherPriority.Background, new EventAppHandle(UpdateIsoFilesControl), arg);
                    }
                    break;
                case AppPhoneAction.Uninstall:
                    {
                        var result = MessageBox.Show(string.Format(AppRes.QUinstall, temp.Name), AppRes.TitleWindows,
                                                 MessageBoxButton.YesNo, MessageBoxImage.Question);
                        if (result == MessageBoxResult.Yes)
                        {
                            if (WPhoneDevice.CurrentDevice == null || (WPhoneDevice.CurrentDevice != null && !WPhoneDevice.CurrentDevice.IsConnected()))
                            {
                                MessageBox.Show(AppRes.ConnectionLost, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Warning);
                                return;
                            }
                            CelPhoneMsg.Tag = CelPhoneMsg.Text;
                            CelPhoneMsg.Text = AppRes.WaitUinstall;
                            PanelAppsInst.expAppIns.IsEnabled = false;
                            Dispatcher.BeginInvoke(DispatcherPriority.Background, new EventAppHandle(UninstallApp), temp);
                        }
                    }
                    break;
                case AppPhoneAction.RenameCache:
                    {
                        var newname = string.Empty;
                        var result = InputBoxControl.InputBox(AppRes.TitleWindows, AppRes.NewAlias, ref newname);
                        if (result == DialogResult.OK)
                        {
                            if (WPhoneDevice.CurrentDevice == null || (WPhoneDevice.CurrentDevice != null && !WPhoneDevice.CurrentDevice.IsConnected()))
                            {
                                MessageBox.Show(AppRes.ConnectionLost, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Warning);
                                return;
                            }
                            CelPhoneMsg.Tag = CelPhoneMsg.Text;
                            CelPhoneMsg.Text = AppRes.WaitAlias;
                            PanelAppsInst.expAppIns.IsEnabled = false;
                            temp.Alias = newname;
                            Dispatcher.BeginInvoke(DispatcherPriority.Background, new EventAppHandle(AliasApp), temp);
                        }
                    }
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        private delegate void EventAppHandle(AppPhoneEvent arg);

        private void LaunchApp(AppPhoneEvent arg)
        {
            try
            {
                var oldcur = Cursor;
                Cursor = System.Windows.Input.Cursors.Wait;
                WPhoneDevice.CurrentDevice.GetApplication(new Guid(arg.Guid)).Launch();
                WPhoneDevice.CurrentDevice.Activate();
                Cursor = oldcur;
            }
            catch (Exception ex)
            {
                MessageBox.Show(AppRes.LaunchError + ex.Message, AppRes.TitleWindows);
            }
            CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
            PanelExplorer.TreeView.IsEnabled = true;
        }

        private void AliasApp(AppPhoneEvent arg)
        {
            try
            {
                var oldcur = Cursor;
                Cursor = System.Windows.Input.Cursors.Wait;
                var item = WpIsolateSaveData.Current.WpApplication.Find(a => a.Guid == arg.Guid);
                if (item != null)
                {
                    item.RenameTitle = arg.Alias;
                }
                else
                {
                    item = new WpDeployApplication { Guid = arg.Guid, Title = arg.Name, RenameTitle = arg.Alias };
                }
                WpIsolateSaveData.Current.AddData(item);
                WpIsolateSaveData.Save();
                PanelAppsInst.RemoteApplications = WPhoneDevice.ListApplicationsInstalled();
                PanelAppsInst.expAppIns.IsEnabled = true;
                PanelAppsInst.Expanded = true;
                Cursor = oldcur;
            }
            catch (Exception ex)
            {
                MessageBox.Show(AppRes.AliasError + ex.Message, AppRes.TitleWindows);
            }
            CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
        }

        private void UninstallApp(AppPhoneEvent arg)
        {
            try
            {
                var oldcur = Cursor;
                Cursor = System.Windows.Input.Cursors.Wait;
                WPhoneDevice.CurrentDevice.GetApplication(new Guid(arg.Guid)).TerminateRunningInstances();
                WPhoneDevice.CurrentDevice.GetApplication(new Guid(arg.Guid)).Uninstall();
                PanelAppsInst.RemoteApplications = WPhoneDevice.ListApplicationsInstalled();
                PanelAppsInst.expAppIns.IsEnabled = true;
                PanelAppsInst.Expanded = true;
                Cursor = oldcur;
            }
            catch (Exception ex)
            {
                MessageBox.Show(AppRes.UninstallError + ex.Message, AppRes.TitleWindows);
            }
            CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
            PanelExplorer.TreeView.IsEnabled = true;
        }

        private void PanelDeployUploadCommand(object sender, RoutedEventArgs e)
        {
            if (WPhoneDevice.CurrentDevice == null || (WPhoneDevice.CurrentDevice != null && !WPhoneDevice.CurrentDevice.IsConnected()))
            {
                MessageBox.Show(AppRes.ConnectionLost, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            PanelDeploy.BntNewDeploy.IsEnabled = false;
            PanelDeploy.BntUpdDeploy.IsEnabled = false;
            PanelDeploy.BntCache.IsEnabled = false;
            PanelDeploy.fileUpload.IsEnabled = false;
            PanelDeploy.Chklaunch.IsEnabled = false;
            var temp = (UploadPhoneEvent)e;
            CelPhoneMsg.Tag = CelPhoneMsg.Text;
            if (temp.NewDeploy)
            {
                CelPhoneMsg.Text = AppRes.WaitDeploy;
                Dispatcher.BeginInvoke(DispatcherPriority.Background, new UploadAppHandle(NewDeploy), temp);
            }
            else
            {
                CelPhoneMsg.Text = AppRes.WaitUpdate;
                Dispatcher.BeginInvoke(DispatcherPriority.Background, new UploadAppHandle(UpdDeploy), temp);
            }

        }

        private void UpdateIsoFilesControl(AppPhoneEvent arg)
        {
            var oldcur = Cursor;
            Cursor = System.Windows.Input.Cursors.Wait;
            PanelExplorer.Application = null;
            PanelExplorer.Application = arg.Guid;
            CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
            PanelExplorer.TreeView.IsEnabled = true;
            Cursor = oldcur;
        }

        private delegate void UploadAppHandle(UploadPhoneEvent arg);

        private void UpdDeploy(UploadPhoneEvent arg)
        {
            var oldcur = Cursor;
            Cursor = System.Windows.Input.Cursors.Wait;
            try
            {
                var existingInstall = WPhoneDevice.CurrentDevice.GetApplication(new Guid(arg.Guid));
                existingInstall.TerminateRunningInstances();
                existingInstall.UpdateApplication(arg.Genre, arg.Icon, arg.Filexap);
                if (arg.LaunchAfter)
                {
                    existingInstall.Launch();
                    WPhoneDevice.CurrentDevice.Activate();
                }
            }
            catch (OutOfMemoryException ex)
            {
                Cursor = oldcur;
                MessageBox.Show(AppRes.OutOfMemoryDevice + ex.Message);
            }
            catch (Exception ex)
            {
                Cursor = oldcur;
                MessageBox.Show(AppRes.UpdateError + ex.Message, AppRes.TitleWindows);
            }
            Cursor = System.Windows.Input.Cursors.Wait;
            PanelDeploy.Clearxap();
            try
            {
                PanelAppsInst.RemoteApplications = WPhoneDevice.ListApplicationsInstalled();
            }
            catch
            {

                PanelAppsInst.RemoteApplications = null;
            }
            PanelAppsInst.expAppIns.IsEnabled = true;
            PanelAppsInst.Expanded = true;
            CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
            Cursor = oldcur;
        }

        private void NewDeploy(UploadPhoneEvent arg)
        {
            var oldcur = Cursor;
            Cursor = System.Windows.Input.Cursors.Wait;
            try
            {
                if (WPhoneDevice.CurrentDevice.IsApplicationInstalled(new Guid(arg.Guid)))
                {
                    var existingInstall = WPhoneDevice.CurrentDevice.GetApplication(new Guid(arg.Guid));
                    existingInstall.TerminateRunningInstances();
                    existingInstall.Uninstall();
                }

                WPhoneDevice.CurrentDevice.InstallApplication(new Guid(arg.Guid), Guid.Empty, arg.Genre, arg.Icon, arg.Filexap);
                if (arg.LaunchAfter)
                {
                    var existingInstall = WPhoneDevice.CurrentDevice.GetApplication(new Guid(arg.Guid));
                    existingInstall.Launch();
                    WPhoneDevice.CurrentDevice.Activate();
                }
            }
            catch (OutOfMemoryException ex)
            {
                Cursor = oldcur;
                MessageBox.Show(AppRes.OutOfMemoryDevice + ex.Message);
            }
            catch (Exception ex)
            {
                Cursor = oldcur;
                MessageBox.Show(AppRes.DeployError + ex.Message, AppRes.TitleWindows);
            }
            Cursor = System.Windows.Input.Cursors.Wait;
            PanelDeploy.Clearxap();
            try
            {
                PanelAppsInst.RemoteApplications = WPhoneDevice.ListApplicationsInstalled();
            }
            catch
            {

                PanelAppsInst.RemoteApplications = null;
            }
            PanelAppsInst.expAppIns.IsEnabled = true;
            PanelAppsInst.Expanded = true;
            CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
            Cursor = oldcur;
        }

        private delegate void ExplorerCommandHandle(object[] args);

        private void CopyDir(object[] args)
        {
            var oldcur = Cursor;
            Cursor = System.Windows.Input.Cursors.Wait;
            var temp = (ExplorerPhoneEvent)args[0];
            var closeapp = (bool)args[1];
            var desktopfolder = (string)args[2];
            var olnysel = (bool)args[3];
            try
            {
                if (closeapp)
                {
                    var existingInstall = WPhoneDevice.CurrentDevice.GetApplication(new Guid(temp.Guid));
                    existingInstall.TerminateRunningInstances();
                }
                var qtddir = 0;
                var qtdfiles = 0;
                if (!Directory.Exists(desktopfolder))
                {
                    Directory.CreateDirectory(desktopfolder);
                }
                desktopfolder = Path.Combine(desktopfolder, ((TreeViewWithIcons)PanelExplorer.TreeView.Items[0]).HeaderText);
                if (Directory.Exists(desktopfolder))
                {
                    Directory.Delete(desktopfolder, true);
                }
                desktopfolder = Directory.CreateDirectory(desktopfolder).FullName;

                var filesnotcopy = WPhoneDevice.CopyIsoDir(temp.Guid, temp.IsoFileInfo, desktopfolder, olnysel, ref qtddir, ref qtdfiles);

                PanelExplorer.TreeView.IsEnabled = true;
                CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
                if (olnysel)
                {
                    //refresh
                    PanelExplorer.Application = null;
                    PanelExplorer.Application = temp.Guid;
                }

                var msg = AppRes.FolderCop + qtddir.ToString(CultureInfo.InvariantCulture) + "\n";
                msg += AppRes.FileCop + qtdfiles.ToString(CultureInfo.InvariantCulture) + "\n";
                var msgerr = filesnotcopy.Aggregate(string.Empty, (current, s) => current + (s + "\n"));
                if (msgerr.Length != 0)
                {
                    Cursor = oldcur;
                    msg += "\n" + AppRes.Errors + "\n" + msgerr;
                    MessageBox.Show(msg, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    System.Diagnostics.Process.Start("explorer.exe", desktopfolder);
                }
            }
            catch (Exception ex)
            {
                Cursor = oldcur;
                PanelExplorer.TreeView.IsEnabled = true;
                CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
                //refresh
                PanelExplorer.Application = null;
                PanelExplorer.Application = temp.Guid;
                MessageBox.Show(AppRes.ErrCopFolder + ex.Message, AppRes.TitleWindows);
            }
            Cursor = oldcur;
        }

        private void DeleteAllFiles(object[] args)
        {
            var oldcur = Cursor;
            Cursor = System.Windows.Input.Cursors.Wait;
            var temp = (ExplorerPhoneEvent)args[0];
            var closeapp = (bool)args[1];
            var errors = string.Empty;
            var qtdfiles = 0;
            try
            {
                if (closeapp)
                {
                    var existingInstall = WPhoneDevice.CurrentDevice.GetApplication(new Guid(temp.Guid));
                    existingInstall.TerminateRunningInstances();
                }
                foreach (var err in from item in temp.IsoFileInfo.Files where !item.IsDiretory && !item.IsRoot && !item.IsSystem select WPhoneDevice.DeleteFile(temp.Guid, temp.IsoFileInfo, item.Name))
                {
                    if (err.Length == 0)
                    {
                        qtdfiles++;
                    }
                    else
                    {
                        errors += err + "\n";
                    }
                }
                PanelExplorer.TreeView.IsEnabled = true;
                if (qtdfiles > 0)
                {
                    PanelExplorer.Application = null;
                    PanelExplorer.Application = temp.Guid;
                }
                CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
                var msg = AppRes.FilesDel + qtdfiles.ToString(CultureInfo.InvariantCulture);
                if (errors.Length != 0)
                {
                    Cursor = oldcur;
                    msg += AppRes.Errors + "\n" + errors;
                    MessageBox.Show(msg, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                PanelExplorer.TreeView.IsEnabled = true;
                PanelExplorer.Application = null;
                PanelExplorer.Application = temp.Guid;
                CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
                Cursor = oldcur;
                MessageBox.Show(AppRes.ErrDelFilesInFolder + ex.Message, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
            }
            Cursor = oldcur;
        }

        private void DeleteSeletcFiles(object[] args)
        {
            var oldcur = Cursor;
            Cursor = System.Windows.Input.Cursors.Wait;
            var temp = (ExplorerPhoneEvent)args[0];
            var closeapp = (bool)args[1];
            var qtdfiles = 0;
            try
            {
                if (closeapp)
                {
                    var existingInstall = WPhoneDevice.CurrentDevice.GetApplication(new Guid(temp.Guid));
                    existingInstall.TerminateRunningInstances();
                }
                var filesnotdel = WPhoneDevice.deleteSelectedIsoDir(temp.Guid, temp.IsoFileInfo.Files, ref qtdfiles);
                PanelExplorer.TreeView.IsEnabled = true;
                if (qtdfiles > 0)
                {
                    PanelExplorer.Application = null;
                    PanelExplorer.Application = temp.Guid;
                }
                CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
                var msg = AppRes.FilesDel + qtdfiles.ToString(CultureInfo.InvariantCulture);
                var msgerr = filesnotdel.Aggregate(string.Empty, (current, s) => current + (s + "\n"));
                if (msgerr.Length != 0)
                {
                    Cursor = oldcur;
                    msg += "\n" + AppRes.Errors + "\n" + msgerr;
                    MessageBox.Show(msg, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                PanelExplorer.TreeView.IsEnabled = true;
                PanelExplorer.Application = null;
                PanelExplorer.Application = temp.Guid;
                CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
                Cursor = oldcur;
                MessageBox.Show(AppRes.ErrDelFilesSeleted + ex.Message, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
            }
            Cursor = oldcur;
        }

        private void DeleteDir(object[] args)
        {
            var oldcur = Cursor;
            Cursor = System.Windows.Input.Cursors.Wait;
            var temp = (ExplorerPhoneEvent)args[0];
            var closeapp = (bool)args[1];
            try
            {
                if (closeapp)
                {
                    var existingInstall = WPhoneDevice.CurrentDevice.GetApplication(new Guid(temp.Guid));
                    existingInstall.TerminateRunningInstances();
                }
                WPhoneDevice.DeleteIsoDir(temp.Guid, temp.IsoFileInfo);
                PanelExplorer.Application = null;
                PanelExplorer.Application = temp.Guid;
                PanelExplorer.TreeView.IsEnabled = true;
                CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
            }
            catch (Exception ex)
            {
                PanelExplorer.TreeView.IsEnabled = true;
                PanelExplorer.Application = null;
                PanelExplorer.Application = temp.Guid;
                CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
                Cursor = oldcur;
                MessageBox.Show(AppRes.ErrDelFolder + ex.Message, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
            }
            Cursor = oldcur;
        }

        private void AddFiles(object[] args)
        {
            var oldcur = Cursor;
            Cursor = System.Windows.Input.Cursors.Wait;
            var temp = (ExplorerPhoneEvent)args[0];
            var fileNames = (string[])args[1];
            var errors = string.Empty;
            var qtdfiles = 0;
            try
            {
                foreach (var err in fileNames.Select(file => WPhoneDevice.CopySendFile(temp.Guid, temp.IsoFileInfo, file, true)))
                {
                    if (err.Length == 0)
                    {
                        qtdfiles++;
                    }
                    else
                    {
                        errors += err + "\n";
                    }
                }
                if (qtdfiles > 0)
                {
                    PanelExplorer.TreeView.IsEnabled = true;
                    PanelExplorer.Application = null;
                    PanelExplorer.Application = temp.Guid;
                    CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
                }
                var msg = AppRes.FileCop + qtdfiles.ToString(CultureInfo.InvariantCulture);
                if (errors.Length != 0)
                {
                    Cursor = oldcur;
                    msg += AppRes.Errors + "\n" + errors;
                    MessageBox.Show(msg, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                PanelExplorer.TreeView.IsEnabled = true;
                PanelExplorer.Application = null;
                PanelExplorer.Application = temp.Guid;
                CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
                Cursor = oldcur;
                MessageBox.Show(AppRes.ErrCopFiles + ex.Message, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
            }
            Cursor = oldcur;
        }

        private void CreateFolder(object[] args)
        {
            var oldcur = Cursor;
            Cursor = System.Windows.Input.Cursors.Wait;
            var temp = (ExplorerPhoneEvent)args[0];
            var newforder = (string)args[1];
            try
            {
                var error = WPhoneDevice.CreateIsoDir(temp.Guid, temp.IsoFileInfo, newforder);
                PanelExplorer.TreeView.IsEnabled = true;
                PanelExplorer.Application = null;
                PanelExplorer.Application = temp.Guid;
                CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
                if (error.Length != 0)
                {
                    Cursor = oldcur;
                    MessageBox.Show(error, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                PanelExplorer.TreeView.IsEnabled = true;
                PanelExplorer.Application = null;
                PanelExplorer.Application = temp.Guid;
                CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
                Cursor = oldcur;
                MessageBox.Show(AppRes.ErrCreateFolder + ex.Message, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
            }
            Cursor = oldcur;
        }

        private void CopyFile(object[] args)
        {
            var oldcur = Cursor;
            Cursor = System.Windows.Input.Cursors.Wait;
            var temp = (ExplorerPhoneEvent)args[0];
            var closeapp = (bool)args[1];
            var desktopfolder = (string)args[2];
            try
            {
                if (closeapp)
                {
                    var existingInstall = WPhoneDevice.CurrentDevice.GetApplication(new Guid(temp.Guid));
                    existingInstall.TerminateRunningInstances();
                }
                if (!Directory.Exists(desktopfolder))
                {
                    Directory.CreateDirectory(desktopfolder);
                }
                desktopfolder = Path.Combine(desktopfolder, ((TreeViewWithIcons)PanelExplorer.TreeView.Items[0]).HeaderText);
                if (Directory.Exists(desktopfolder))
                {
                    Directory.Delete(desktopfolder, true);
                }
                desktopfolder = Directory.CreateDirectory(desktopfolder).FullName;
                WPhoneDevice.CopyReceiveFile(temp.Guid, temp.IsoFileInfo, desktopfolder);
                PanelExplorer.TreeView.IsEnabled = true;
                PanelExplorer.Application = null;
                PanelExplorer.Application = temp.Guid;
                CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
                System.Diagnostics.Process.Start("explorer.exe", desktopfolder);
            }
            catch (Exception ex)
            {
                PanelExplorer.TreeView.IsEnabled = true;
                PanelExplorer.Application = null;
                PanelExplorer.Application = temp.Guid;
                CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
                Cursor = oldcur;
                MessageBox.Show(AppRes.ErrCopFiles + ex.Message, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
            }
            Cursor = oldcur;
        }

        private void DeleteFile(object[] args)
        {
            var oldcur = Cursor;
            Cursor = System.Windows.Input.Cursors.Wait;
            var temp = (ExplorerPhoneEvent)args[0];
            var closeapp = (bool)args[1];
            try
            {
                if (closeapp)
                {
                    var existingInstall = WPhoneDevice.CurrentDevice.GetApplication(new Guid(temp.Guid));
                    existingInstall.TerminateRunningInstances();
                }
                WPhoneDevice.DeleteFile(temp.Guid, temp.IsoFileInfo, string.Empty);
                PanelExplorer.TreeView.IsEnabled = true;
                PanelExplorer.Application = null;
                PanelExplorer.Application = temp.Guid;
                CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
            }
            catch (Exception ex)
            {
                PanelExplorer.TreeView.IsEnabled = true;
                PanelExplorer.Application = null;
                PanelExplorer.Application = temp.Guid;
                CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
                Cursor = oldcur;
                MessageBox.Show(AppRes.ErrDelFile + ex.Message, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
            }
            Cursor = oldcur;
        }

        private void RenameFile(object[] args)
        {
            var oldcur = Cursor;
            Cursor = System.Windows.Input.Cursors.Wait;
            var temp = (ExplorerPhoneEvent)args[0];
            var closeapp = (bool)args[1];
            var newfile = (string)args[2];
            try
            {
                if (closeapp)
                {
                    var existingInstall = WPhoneDevice.CurrentDevice.GetApplication(new Guid(temp.Guid));
                    existingInstall.TerminateRunningInstances();
                }
                WPhoneDevice.RenameFile(temp.Guid, temp.IsoFileInfo, newfile);
                PanelExplorer.TreeView.IsEnabled = true;
                PanelExplorer.Application = null;
                PanelExplorer.Application = temp.Guid;
                CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
            }
            catch (Exception ex)
            {
                PanelExplorer.TreeView.IsEnabled = true;
                PanelExplorer.Application = null;
                PanelExplorer.Application = temp.Guid;
                CelPhoneMsg.Text = CelPhoneMsg.Tag.ToString();
                Cursor = oldcur;
                MessageBox.Show(AppRes.ErrRenFile + ex.Message, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
            }
            Cursor = oldcur;
        }

        private void PanelExplorerCommand(object sender, RoutedEventArgs e)
        {
            if (WPhoneDevice.CurrentDevice == null || (WPhoneDevice.CurrentDevice != null && !WPhoneDevice.CurrentDevice.IsConnected()))
            {
                MessageBox.Show(AppRes.ConnectionLost, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            var temp = (ExplorerPhoneEvent)e;
            if (temp.IsoFileInfo.IsRoot || temp.IsoFileInfo.IsDiretory)
            {
                //folder commands
                switch (temp.Command)
                {
                    case "Launch":
                        {
                            PanelExplorer.TreeView.IsEnabled = false;
                            CelPhoneMsg.Tag = CelPhoneMsg.Text;
                            CelPhoneMsg.Text = AppRes.WaitLaunch;
                            var arg = new AppPhoneEvent(AppPhoneAction.Launch, string.Empty, temp.Guid, string.Empty);
                            Dispatcher.BeginInvoke(DispatcherPriority.Background, new EventAppHandle(LaunchApp), arg);
                        }
                        break;
                    case "Refresh":
                        {
                            PanelExplorer.TreeView.IsEnabled = false;
                            CelPhoneMsg.Tag = CelPhoneMsg.Text;
                            CelPhoneMsg.Text = AppRes.WaitReadFiles;
                            var arg = new AppPhoneEvent(AppPhoneAction.None, string.Empty, temp.Guid, string.Empty);
                            Dispatcher.BeginInvoke(DispatcherPriority.Background, new EventAppHandle(UpdateIsoFilesControl), arg);
                        }
                        break;
                    case "Remove":
                        {
                            var result = MessageBox.Show(string.Format(AppRes.QUinstall, ""), AppRes.TitleWindows,
                                                         MessageBoxButton.YesNo, MessageBoxImage.Question);
                            if (result == MessageBoxResult.Yes)
                            {
                                if (WPhoneDevice.CurrentDevice == null || (WPhoneDevice.CurrentDevice != null && !WPhoneDevice.CurrentDevice.IsConnected()))
                                {
                                    MessageBox.Show(AppRes.ConnectionLost, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Warning);
                                    return;
                                }
                                PanelExplorer.TreeView.IsEnabled = false;
                                CelPhoneMsg.Tag = CelPhoneMsg.Text;
                                CelPhoneMsg.Text = AppRes.WaitUinstall;
                                PanelAppsInst.expAppIns.IsEnabled = false;
                                PanelExplorer.Application = null;
                                ShowPanelApps();
                                var arg = new AppPhoneEvent(AppPhoneAction.Uninstall, string.Empty, temp.Guid, string.Empty);
                                Dispatcher.BeginInvoke(DispatcherPriority.Background, new EventAppHandle(UninstallApp), arg);
                            }
                        }
                        break;
                    case "Copy":
                    case "CopyFilesSeleted":
                        {
                            var onlysel = temp.Command == "CopyFilesSeleted";
                            string desktopfolder;
                            var folderDIalog = new FolderBrowserDialog { Description = AppRes.DescFolderCopy };

                            if (folderDIalog.ShowDialog() == DialogResult.OK)
                            {
                                desktopfolder = folderDIalog.SelectedPath;
                                var deskDirinfo = new DirectoryInfo(desktopfolder);
                                if (deskDirinfo.Root.FullName == deskDirinfo.FullName)
                                {
                                    MessageBox.Show(AppRes.ErrRootDel, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Exclamation);
                                    return;
                                }
                                if (temp.IsoFileInfo.Files == null)
                                {
                                    MessageBox.Show(AppRes.FolderEmpty, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Exclamation);
                                    return;
                                }
                                var desktopapp = Path.Combine(desktopfolder, ((TreeViewWithIcons)PanelExplorer.TreeView.Items[0]).HeaderText);
                                if (Directory.Exists(desktopapp))
                                {
                                    var result = MessageBox.Show(string.Format(AppRes.QDelDir,((TreeViewWithIcons)PanelExplorer.TreeView.Items[0]).HeaderText), AppRes.TitleWindows,
                                            MessageBoxButton.YesNo, MessageBoxImage.Question);
                                    if (result == MessageBoxResult.No)
                                    {
                                        return;
                                    }
                                }
                                if (WPhoneDevice.CurrentDevice == null || (WPhoneDevice.CurrentDevice != null && !WPhoneDevice.CurrentDevice.IsConnected()))
                                {
                                    MessageBox.Show(AppRes.ConnectionLost, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Warning);
                                    return;
                                }
                            }
                            else
                            {
                                return;
                            }
                            var closeapp = false;
                            if (PanelExplorer.ChkAppRun.IsChecked.HasValue && PanelExplorer.ChkAppRun.IsChecked.Value)
                            {
                                var result = MessageBox.Show(AppRes.CloseInstance, AppRes.TitleWindows,
                                                                MessageBoxButton.YesNo, MessageBoxImage.Question);
                                if (result == MessageBoxResult.Yes)
                                {
                                    closeapp = true;
                                }
                                if (WPhoneDevice.CurrentDevice == null || (WPhoneDevice.CurrentDevice != null && !WPhoneDevice.CurrentDevice.IsConnected()))
                                {
                                    MessageBox.Show(AppRes.ConnectionLost, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Warning);
                                    return;
                                }
                            }
                            PanelExplorer.TreeView.IsEnabled = false;
                            CelPhoneMsg.Tag = CelPhoneMsg.Text;
                            CelPhoneMsg.Text = AppRes.WaitCopyFolder;
                            var args = new List<object> { temp, closeapp, desktopfolder, onlysel };
                            Dispatcher.BeginInvoke(DispatcherPriority.Background, new ExplorerCommandHandle(CopyDir), args.ToArray());
                        }
                        break;
                    case "DeleteFilesSeleted":
                        {
                            var result = MessageBox.Show(AppRes.QDelSeleted, AppRes.TitleWindows,
                                                         MessageBoxButton.YesNo, MessageBoxImage.Question);
                            if (result == MessageBoxResult.Yes)
                            {
                                if (WPhoneDevice.CurrentDevice == null || (WPhoneDevice.CurrentDevice != null && !WPhoneDevice.CurrentDevice.IsConnected()))
                                {
                                    MessageBox.Show(AppRes.ConnectionLost, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Warning);
                                    return;
                                }
                                var closeapp = false;
                                if (PanelExplorer.ChkAppRun.IsChecked.HasValue && PanelExplorer.ChkAppRun.IsChecked.Value)
                                {
                                    result = MessageBox.Show(AppRes.CloseInstance, AppRes.TitleWindows,
                                                                    MessageBoxButton.YesNo, MessageBoxImage.Question);
                                    if (result == MessageBoxResult.Yes)
                                    {
                                        closeapp = true;
                                    }
                                    if (WPhoneDevice.CurrentDevice == null || (WPhoneDevice.CurrentDevice != null && !WPhoneDevice.CurrentDevice.IsConnected()))
                                    {
                                        MessageBox.Show(AppRes.ConnectionLost, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Warning);
                                        return;
                                    }
                                }
                                PanelExplorer.TreeView.IsEnabled = false;
                                CelPhoneMsg.Tag = CelPhoneMsg.Text;
                                CelPhoneMsg.Text = AppRes.WaitDelFilesFolder;
                                var args = new List<object> { temp, closeapp };
                                Dispatcher.BeginInvoke(DispatcherPriority.Background, new ExplorerCommandHandle(DeleteSeletcFiles), args.ToArray());
                            }
                        }
                        break;
                    case "DeleteAll":
                        {
                            var result = MessageBox.Show(AppRes.QDelAllFiles, AppRes.TitleWindows,
                                                         MessageBoxButton.YesNo, MessageBoxImage.Question);
                            if (result == MessageBoxResult.Yes)
                            {
                                if (WPhoneDevice.CurrentDevice == null || (WPhoneDevice.CurrentDevice != null && !WPhoneDevice.CurrentDevice.IsConnected()))
                                {
                                    MessageBox.Show(AppRes.ConnectionLost, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Warning);
                                    return;
                                }
                                var closeapp = false;
                                if (PanelExplorer.ChkAppRun.IsChecked.HasValue && PanelExplorer.ChkAppRun.IsChecked.Value)
                                {
                                    result = MessageBox.Show(AppRes.CloseInstance, AppRes.TitleWindows,
                                                                    MessageBoxButton.YesNo, MessageBoxImage.Question);
                                    if (result == MessageBoxResult.Yes)
                                    {
                                        closeapp = true;
                                    }
                                    if (WPhoneDevice.CurrentDevice == null || (WPhoneDevice.CurrentDevice != null && !WPhoneDevice.CurrentDevice.IsConnected()))
                                    {
                                        MessageBox.Show(AppRes.ConnectionLost, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Warning);
                                        return;
                                    }
                                }
                                PanelExplorer.TreeView.IsEnabled = false;
                                CelPhoneMsg.Tag = CelPhoneMsg.Text;
                                CelPhoneMsg.Text = AppRes.WaitDelFilesFolder;
                                var args = new List<object> { temp, closeapp };
                                Dispatcher.BeginInvoke(DispatcherPriority.Background, new ExplorerCommandHandle(DeleteAllFiles), args.ToArray());
                            }
                        }
                        break;
                    case "Delete":
                        {
                            var result = MessageBox.Show(AppRes.QDelFolder, AppRes.TitleWindows,
                                                         MessageBoxButton.YesNo, MessageBoxImage.Question);
                            if (result == MessageBoxResult.Yes)
                            {
                                if (WPhoneDevice.CurrentDevice == null || (WPhoneDevice.CurrentDevice != null && !WPhoneDevice.CurrentDevice.IsConnected()))
                                {
                                    MessageBox.Show(AppRes.ConnectionLost, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Warning);
                                    return;
                                }
                                var closeapp = false;
                                if (PanelExplorer.ChkAppRun.IsChecked.HasValue && PanelExplorer.ChkAppRun.IsChecked.Value)
                                {
                                    result = MessageBox.Show(AppRes.CloseInstance, AppRes.TitleWindows,
                                                                    MessageBoxButton.YesNo, MessageBoxImage.Question);
                                    if (result == MessageBoxResult.Yes)
                                    {
                                        closeapp = true;
                                    }
                                    if (WPhoneDevice.CurrentDevice == null || (WPhoneDevice.CurrentDevice != null && !WPhoneDevice.CurrentDevice.IsConnected()))
                                    {
                                        MessageBox.Show(AppRes.ConnectionLost, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Warning);
                                        return;
                                    }
                                }
                                PanelExplorer.TreeView.IsEnabled = false;
                                CelPhoneMsg.Tag = CelPhoneMsg.Text;
                                CelPhoneMsg.Text = AppRes.WaitDelFolder;
                                var args = new List<object> { temp, closeapp };
                                Dispatcher.BeginInvoke(DispatcherPriority.Background, new ExplorerCommandHandle(DeleteDir), args.ToArray());
                            }
                        }
                        break;
                    case "AddFiles":
                        {
                            var openfiles = new OpenFileDialog { Multiselect = true, Title = AppRes.SeletFilesAdd };
                            if (openfiles.ShowDialog() == true)
                            {
                                if (WPhoneDevice.CurrentDevice == null || (WPhoneDevice.CurrentDevice != null && !WPhoneDevice.CurrentDevice.IsConnected()))
                                {
                                    MessageBox.Show(AppRes.ConnectionLost, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Warning);
                                    return;
                                }
                                CelPhoneMsg.Tag = CelPhoneMsg.Text;
                                CelPhoneMsg.Text = AppRes.WaitAddFile;
                                PanelExplorer.TreeView.IsEnabled = false;
                                var args = new List<object> { temp, openfiles.FileNames };
                                Dispatcher.BeginInvoke(DispatcherPriority.Background, new ExplorerCommandHandle(AddFiles), args.ToArray());
                            }
                        }
                        break;
                    case "CreateFolder":
                        {
                            var newforder = string.Empty;
                            var result = InputBoxControl.InputBox(AppRes.TitleWindows, AppRes.FolderName, ref newforder);
                            if (result == DialogResult.OK)
                            {
                                if (string.IsNullOrEmpty(newforder))
                                {
                                    MessageBox.Show(AppRes.FoderNameEmpty, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
                                    return;
                                }
                                if (WPhoneDevice.CurrentDevice == null || (WPhoneDevice.CurrentDevice != null && !WPhoneDevice.CurrentDevice.IsConnected()))
                                {
                                    MessageBox.Show(AppRes.ConnectionLost, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Warning);
                                    return;
                                }
                                CelPhoneMsg.Tag = CelPhoneMsg.Text;
                                CelPhoneMsg.Text = AppRes.WaitCreateFolder;
                                PanelExplorer.TreeView.IsEnabled = false;
                                var args = new List<object> { temp, newforder };
                                Dispatcher.BeginInvoke(DispatcherPriority.Background, new ExplorerCommandHandle(CreateFolder), args.ToArray());
                            }
                        }
                        break;
                }
            }
            else // files commands
            {
                switch (temp.Command)
                {
                    case "Copy":
                        {
                            string desktopfolder;
                            var folderDIalog = new FolderBrowserDialog { Description = AppRes.DescFolderCopy };
                            if (folderDIalog.ShowDialog() == DialogResult.OK)
                            {
                                desktopfolder = folderDIalog.SelectedPath;
                                var desktopapp = Path.Combine(desktopfolder, ((TreeViewWithIcons)PanelExplorer.TreeView.Items[0]).HeaderText);
                                if (Directory.Exists(desktopapp))
                                {
                                    var result = MessageBox.Show(string.Format(AppRes.QDelDir, ((TreeViewWithIcons)PanelExplorer.TreeView.Items[0]).HeaderText), AppRes.TitleWindows,
                                            MessageBoxButton.YesNo, MessageBoxImage.Question);
                                    if (result == MessageBoxResult.No)
                                    {
                                        return;
                                    }
                                }
                                if (WPhoneDevice.CurrentDevice == null || (WPhoneDevice.CurrentDevice != null && !WPhoneDevice.CurrentDevice.IsConnected()))
                                {
                                    MessageBox.Show(AppRes.ConnectionLost, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Warning);
                                    return;
                                }
                            }
                            else
                            {
                                return;
                            }
                            var closeapp = false;
                            if (PanelExplorer.ChkAppRun.IsChecked.HasValue && PanelExplorer.ChkAppRun.IsChecked.Value)
                            {

                                var result = MessageBox.Show(AppRes.CloseInstance, AppRes.TitleWindows,
                                                                MessageBoxButton.YesNo, MessageBoxImage.Question);
                                if (result == MessageBoxResult.Yes)
                                {
                                    closeapp = true;
                                }
                                if (WPhoneDevice.CurrentDevice == null || (WPhoneDevice.CurrentDevice != null && !WPhoneDevice.CurrentDevice.IsConnected()))
                                {
                                    MessageBox.Show(AppRes.ConnectionLost, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Warning);
                                    return;
                                }
                            }
                            CelPhoneMsg.Tag = CelPhoneMsg.Text;
                            CelPhoneMsg.Text = AppRes.WaitCopFile;
                            PanelExplorer.TreeView.IsEnabled = false;
                            var args = new List<object> { temp, closeapp, desktopfolder };
                            Dispatcher.BeginInvoke(DispatcherPriority.Background, new ExplorerCommandHandle(CopyFile), args.ToArray());
                        }
                        break;
                    case "Delete":
                        {
                            var closeapp = false;
                            if (PanelExplorer.ChkAppRun.IsChecked.HasValue && PanelExplorer.ChkAppRun.IsChecked.Value)
                            {
                                var result = MessageBox.Show(AppRes.CloseInstance, AppRes.TitleWindows,
                                                                MessageBoxButton.YesNo, MessageBoxImage.Question);
                                if (result == MessageBoxResult.Yes)
                                {
                                    closeapp = true;
                                }
                                if (WPhoneDevice.CurrentDevice == null || (WPhoneDevice.CurrentDevice != null && !WPhoneDevice.CurrentDevice.IsConnected()))
                                {
                                    MessageBox.Show(AppRes.ConnectionLost, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Warning);
                                    return;
                                }
                            }
                            CelPhoneMsg.Tag = CelPhoneMsg.Text;
                            CelPhoneMsg.Text = AppRes.WaitDelFile;
                            PanelExplorer.TreeView.IsEnabled = false;
                            var args = new List<object> { temp, closeapp };
                            Dispatcher.BeginInvoke(DispatcherPriority.Background, new ExplorerCommandHandle(DeleteFile), args.ToArray());
                        }
                        break;
                    case "Rename":
                        {
                            var closeapp = false;
                            if (PanelExplorer.ChkAppRun.IsChecked.HasValue && PanelExplorer.ChkAppRun.IsChecked.Value)
                            {
                                var resultmsg = MessageBox.Show(AppRes.CloseInstance, AppRes.TitleWindows,
                                                                    MessageBoxButton.YesNo, MessageBoxImage.Question);
                                if (resultmsg == MessageBoxResult.Yes)
                                {
                                    closeapp = true;
                                }
                                if (WPhoneDevice.CurrentDevice == null || (WPhoneDevice.CurrentDevice != null && !WPhoneDevice.CurrentDevice.IsConnected()))
                                {
                                    MessageBox.Show(AppRes.ConnectionLost, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Warning);
                                    return;
                                }
                            }
                            var newfile = string.Empty;
                            var result = InputBoxControl.InputBox(AppRes.TitleWindows, AppRes.NewName, ref newfile);
                            if (result == DialogResult.OK)
                            {
                                if (string.IsNullOrEmpty(newfile))
                                {
                                    MessageBox.Show(AppRes.NewNameEmpty, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
                                    return;
                                }
                                if (WPhoneDevice.CurrentDevice == null || (WPhoneDevice.CurrentDevice != null && !WPhoneDevice.CurrentDevice.IsConnected()))
                                {
                                    MessageBox.Show(AppRes.ConnectionLost, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Warning);
                                    return;
                                }
                                CelPhoneMsg.Tag = CelPhoneMsg.Text;
                                CelPhoneMsg.Text = AppRes.WaitRenameFile;
                                PanelExplorer.TreeView.IsEnabled = false;
                                var args = new List<object> { temp, closeapp, newfile };
                                Dispatcher.BeginInvoke(DispatcherPriority.Background, new ExplorerCommandHandle(RenameFile), args.ToArray());
                            }
                        }
                        break;
                }
            }
        }

        private void AboutMenuClick(object sender, RoutedEventArgs e)
        {
            ShowPanelWelcome();
        }
    }
}